<template>
  <div class="qualifications-review-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>司机资质审核</span>
          <el-button type="primary" @click="refreshList">刷新列表</el-button>
        </div>
      </template>

      <!-- 审核列表 -->
      <el-table
        v-loading="loading"
        :data="driverList"
        style="width: 100%"
        border
      >
        <el-table-column prop="realName" label="姓名" width="120" />
        <el-table-column prop="idCardNumber" label="身份证号" width="180" />
        <el-table-column prop="vehicleNumber" label="车牌号" width="120" />
        <el-table-column prop="vehicleBrand" label="车辆品牌" width="120" />
        <el-table-column prop="vehicleModel" label="车辆型号" width="120" />
        <el-table-column prop="vehicleColor" label="车辆颜色" width="100" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">未通过</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleView(scope.row)"
            >
              查看详情
            </el-button>
            <!-- 状态0（审核中）和状态2（认证未通过）可以通过 -->
            <el-button
              v-if="scope.row.status === 0 || scope.row.status === 2"
              size="small"
              type="success"
              @click="handleAudit(scope.row, 1)"
            >
              通过
            </el-button>
            <!-- 状态0（审核中）可以不通过 -->
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="danger"
              @click="handleAudit(scope.row, 2)"
            >
              不通过
            </el-button>
            <!-- 状态1（认证通过）可以取消认证 -->
            <el-button
              v-if="scope.row.status === 1"
              size="small"
              type="warning"
              @click="handleCancelCertification(scope.row)"
            >
              取消认证
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="司机资质详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ currentDriver.realName }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ currentDriver.idCardNumber }}</el-descriptions-item>
        <el-descriptions-item label="驾驶证号">{{ currentDriver.drivingLicenseNumber }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ currentDriver.vehicleNumber }}</el-descriptions-item>
        <el-descriptions-item label="车辆品牌">{{ currentDriver.vehicleBrand }}</el-descriptions-item>
        <el-descriptions-item label="车辆型号">{{ currentDriver.vehicleModel }}</el-descriptions-item>
        <el-descriptions-item label="车辆颜色">{{ currentDriver.vehicleColor }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="currentDriver.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="currentDriver.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="currentDriver.status === 2" type="danger">未通过</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div class="image-container">
        <div class="image-group">
          <div class="image-title">身份证正面</div>
          <el-image
            style="width: 300px; height: 180px"
            :src="currentDriver.idCardFrontUrl"
            fit="cover"
            :preview-src-list="[currentDriver.idCardFrontUrl]"
          />
        </div>
        <div class="image-group">
          <div class="image-title">身份证背面</div>
          <el-image
            style="width: 300px; height: 180px"
            :src="currentDriver.idCardBackUrl"
            fit="cover"
            :preview-src-list="[currentDriver.idCardBackUrl]"
          />
        </div>
        <div class="image-group">
          <div class="image-title">驾驶证</div>
          <el-image
            style="width: 300px; height: 180px"
            :src="currentDriver.drivingLicenseUrl"
            fit="cover"
            :preview-src-list="[currentDriver.drivingLicenseUrl]"
          />
        </div>
        <div class="image-group">
          <div class="image-title">车辆照片</div>
          <el-image
            style="width: 300px; height: 180px"
            :src="currentDriver.vehiclePhotoUrl"
            fit="cover"
            :preview-src-list="[currentDriver.vehiclePhotoUrl]"
          />
        </div>
        <div class="image-group">
          <div class="image-title">行驶证</div>
          <el-image
            style="width: 300px; height: 180px"
            :src="currentDriver.vehiclePermitUrl"
            fit="cover"
            :preview-src-list="[currentDriver.vehiclePermitUrl]"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <!-- 状态0（审核中）和状态2（认证未通过）可以通过 -->
          <el-button
            v-if="currentDriver.status === 0 || currentDriver.status === 2"
            type="success"
            @click="handleAudit(currentDriver, 1)"
          >
            通过审核
          </el-button>
          <!-- 状态0（审核中）可以不通过 -->
          <el-button
            v-if="currentDriver.status === 0"
            type="danger"
            @click="handleAudit(currentDriver, 2)"
          >
            拒绝审核
          </el-button>
          <!-- 状态1（认证通过）可以取消认证 -->
          <el-button
            v-if="currentDriver.status === 1"
            type="warning"
            @click="handleCancelCertification(currentDriver)"
          >
            取消认证
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDriverAuditList, driverAudit } from '@/api/driver'

// 数据列表
const driverList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentDriver = ref({})

// 获取司机审核列表
const fetchDriverList = async () => {
  try {
    loading.value = true
    const res = await getDriverAuditList()
    if (res.code === 1) {
      driverList.value = res.data
    } else {
      ElMessage.error(res.msg || '获取列表失败')
    }
  } catch (error) {
    console.error('获取司机审核列表错误:', error)
    ElMessage.error('获取列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 刷新列表
const refreshList = () => {
  fetchDriverList()
}

// 查看详情
const handleView = (row) => {
  currentDriver.value = { ...row }
  dialogVisible.value = true
}

// 处理审核
const handleAudit = (driver, status) => {
  const statusText = status === 1 ? '通过' : '不通过'
  
  ElMessageBox.confirm(
    `确定要${statusText}司机 ${driver.realName} 的审核吗？`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        loading.value = true
        const auditData = {
          id: driver.id,
          userId: driver.userId,
          status: status
        }
        
        const res = await driverAudit(auditData)
        
        if (res.code === 1) {
          ElMessage.success(`审核${statusText}成功`)
          dialogVisible.value = false
          fetchDriverList() // 刷新列表
        } else {
          ElMessage.error(res.msg || `审核${statusText}失败`)
        }
      } catch (error) {
        console.error('审核处理错误:', error)
        ElMessage.error(`审核处理失败，请稍后再试`)
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 取消认证
const handleCancelCertification = (driver) => {
  ElMessageBox.confirm(
    `确定要取消司机 ${driver.realName} 的认证吗？取消后该司机将无法接单，需要重新提交认证申请。`,
    '取消认证确认',
    {
      confirmButtonText: '确定取消',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        loading.value = true
        const auditData = {
          id: driver.id,
          userId: driver.userId,
          status: 2 // 状态3表示取消认证
        }
        
        const res = await driverAudit(auditData)
        
        if (res.code === 1) {
          ElMessage.success('取消认证成功')
          dialogVisible.value = false
          fetchDriverList() // 刷新列表
        } else {
          ElMessage.error(res.msg || '取消认证失败')
        }
      } catch (error) {
        console.error('取消认证错误:', error)
        ElMessage.error('取消认证失败，请稍后再试')
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 用户取消操作
    })
}

onMounted(() => {
  fetchDriverList()
})
</script>

<style scoped>
.qualifications-review-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.image-group {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-title {
  margin-bottom: 10px;
  font-weight: bold;
}
</style> 